// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"apiote.xyz/p/szczanieckiej/config"
	"apiote.xyz/p/szczanieckiej/transformers"

	"fmt"
	"io"
	"net/http"
	"regexp"
	"time"

	"golang.org/x/text/transform"
)

type GzmZtm struct {
	client http.Client
}

func (GzmZtm) getTimezone() *time.Location {
	l, _ := time.LoadLocation("Europe/Warsaw")
	return l
}

func (GzmZtm) ConvertVehicles() ([]Vehicle, error) {
	return []Vehicle{}, nil
}

func (z GzmZtm) GetVersions(date time.Time, timezone *time.Location) ([]Version, error) {
	url := "https://otwartedane.metropoliagzm.pl/dataset/rozklady-jazdy-i-lokalizacja-przystankow-gtfs-wersja-rozszerzona"
	response, err := z.client.Get(url)
	if err != nil {
		return []Version{}, fmt.Errorf("GetVersions: cannot GET ‘%s’: %w", url, err)
	}
	doc, err := io.ReadAll(response.Body)
	if err != nil {
		return []Version{}, fmt.Errorf("GetVersions: cannot read whole html: %w", err)
	}

	regex, err := regexp.Compile(`/dataset/rozklady-jazdy-i-lokalizacja-przystankow-gtfs-wersja-rozszerzona/resource/([0-9a-f\-]+)" title="schedule_ZTM_([0-9]{4}).([0-9]{2}).([0-9]{2})_([0-9]+)_([0-9]{4}).zip"`)
	urls := regex.FindAllStringSubmatch(string(doc), -1)

	versions := []Version{}
	for _, u := range urls {
		versions = append(versions, Version{
			Link: "https://otwartedane.metropoliagzm.pl/dataset/rozklady-jazdy-i-lokalizacja-przystankow-gtfs-wersja-rozszerzona/resource/" + u[1] + "/download/schedule_ztm_" + u[2] + "." + u[3] + "." + u[4] + "_" + u[5] + "_" + u[6] + "zip",
		})
	}

	return versions, nil
}

func (GzmZtm) String() string {
	return "gzm_ztm"
}

func (GzmZtm) RealtimeFeeds() map[RealtimeFeedType]string {
	return map[RealtimeFeedType]string{
		TRIP_UPDATES:      "https://gtfsrt.transportgzm.pl:5443/gtfsrt/gzm/tripUpdates",
		VEHICLE_POSITIONS: "https://gtfsrt.transportgzm.pl:5443/gtfsrt/gzm/vehiclePositions",
		ALERTS:            "https://gtfsrt.transoprtgzm.pl:5443/gtfsrt/gzm/info",
	}
}

func (GzmZtm) LuaUpdatesScript(config.Auth) string {
	return ""
}

func (GzmZtm) Transformer() transform.Transformer {
	return transformers.TransformerPL
}

func (GzmZtm) Name() string {
	return "Metropolia GZM ZTM"
}

func (GzmZtm) Flags() FeedFlags {
	return FeedFlags{
		Headsign:     HeadsignTripHeadsing,
		StopIdFormat: "{{stop_id}}",
		StopName:     "{{stop_name}} [{{stop_code}}]",
		LineName:     "{{route_short_name}}",
	}
}

func (GzmZtm) FeedPrepareZip(path string) error {
	return nil
}

func (GzmZtm) QRInfo() (string, QRLocation, string) {
	return "rj.metropoliaztm.pl", QRLocationPath, "/redir/stop/(?<stop>[^/]+)"
}
